package reviewd

import (
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/repo/mgorepo/baser"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"

	creviewd "gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/reviewd"
)

type reviewRepo struct {
	baser.BaseRepo
}

// 新增审核
func (r reviewRepo) AddReview(ctx ddd.Context, review creviewd.ReviewDesc) (id string, err error) {
	ci := &collReview{}
	ci.FullDesc(review)
	ci.ReviewID = r.NextID()
	err = r.DBInsert(ctx, ci)
	if err != nil {
		return "", err
	}
	return ci.ReviewID, nil
}

// 获取指定审核：根据唯一标识获取审核实体
func (r reviewRepo) GetReview(ctx ddd.Context, reviewid string) (*creviewd.ReviewAggregate, error) {
	a, err := r.GetByCollAggregate(ctx, &collReview{ReviewID: reviewid})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	return a.(*creviewd.ReviewAggregate), nil
}

// 分页获取审核列表：根据唯一标识获取下一页指定数量的审核实体集合
// total 总数量
func (r reviewRepo) QueryPage(ctx ddd.Context, is creviewd.ReviewSearch, pi common.PageInfo) (npi common.PageResult, result []creviewd.ReviewAggregate, err error) {
	query := bson.M{
		"targetType": is.TargetType,
		"targetID":   is.TargetID,
	}

	var cs []collReview

	npi, err = r.DBQueryPage(ctx, collNameReview, pi, "_id", query, nil, nil, &cs)

	if err != nil {
		if err == mgo.ErrNotFound {
			err = nil
			npi.End = 1
			return
		}
		err = errors.Wrapf(err, "查询信息失败。查询条件:%v 。分页信息:%v", is, pi)
		return
	}
	if len(cs) == 0 {
		npi.End = 1
		return
	}
	result = make([]creviewd.ReviewAggregate, 0, len(cs))
	for _, c := range cs {
		ia := c.ToReviewAggregate()
		// 初始化聚合
		ia.Init(ia, r.AggregateRoot(), c.ReviewID)
		result = append(result, *ia)
	}
	return
}

// 分页获取审核列表：根据唯一标识获取下一页指定数量的审核实体集合
// total 总数量
func (r reviewRepo) QueryAll(ctx ddd.Context, is creviewd.ReviewSearch) (result []creviewd.ReviewAggregate, err error) {
	query := bson.M{
		"targetType": is.TargetType,
		"targetID":   is.TargetID,
	}

	var cs []collReview

	err = r.DBQuery(ctx, collNameReview, query, nil, nil, &cs)

	if err != nil {
		if err == mgo.ErrNotFound {
			err = nil
			return
		}
		err = errors.Wrapf(err, "查询信息失败。查询条件:%v ", is)
		return
	}
	if len(cs) == 0 {
		return
	}
	result = make([]creviewd.ReviewAggregate, 0, len(cs))
	for _, c := range cs {
		ia := c.ToReviewAggregate()
		// 初始化聚合
		ia.Init(ia, r.AggregateRoot(), c.ReviewID)
		result = append(result, *ia)
	}
	return
}
func (r reviewRepo) DeleteReview(ctx ddd.Context, reviewID string) (err error) {
	return r.DBDestroyID(ctx, collNameReview, reviewID)
}
